﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using StaticView.Resources;
using System.Threading;

namespace StaticView
{
    /*
     * The main page of the application and also the start point
     * 
     * The working process of application
     *      Initialize                      (Constructor)
     *      Calibrate                       (Constructor)
     *          Calibration thread          (Position.Calibrate)
     *              Calibrating...          (ISensor.Calibrate)
     *              Callback                (Position.SensorCallback)
     *          Preparation thread          (Position.PreparationProcess)
     *          Callback                    (CalibrationCallback)
     *      Update                          (Postion.Update)
     */
    public partial class MainPage : PhoneApplicationPage
    {
        Thread updateThread;

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Initialize
            updateThread = new Thread(new ThreadStart(Position.Update));

            // Calibrating
            t_status.Text = "Calibrating...";
            Position.Calibrate(CalibrationCallback);
        }

        // Call after preparation thread is finished
        public void CalibrationCallback(bool AccurateMode)
        {
            // Run update thread, cross-thread call
            Dispatcher.BeginInvoke(() =>
            {
                t_status.Text = "Ready";
                b_viewer.IsEnabled = true;
                updateThread.Start();
            });
        }

        private void b_viewer_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Viewer.xaml", UriKind.Relative));
        }
    }
}